package com.frxuexi.shop.view

import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.ViewGroup.LayoutParams
import android.widget.PopupMenu
import android.widget.PopupWindow
import android.widget.TextView
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.alibaba.android.arouter.facade.Postcard
import com.alibaba.android.arouter.facade.callback.NavigationCallback
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.base.entity.ExplosiveMoney
import com.frxuexi.base.entity.HomeBean
import com.frxuexi.base.entity.ShopBean
import com.frxuexi.base.entity.ShopBeanItem
import com.frxuexi.base.mvi.BaseFragment
import com.frxuexi.base.mvi.RequestType
import com.frxuexi.base.mvi.UiState
import com.frxuexi.base.utils.ArouterManager
import com.frxuexi.shop.R
import com.frxuexi.shop.adapter.ShopAdapter
import com.frxuexi.shop.intent.ShopIntent
import com.frxuexi.shop.viewmodel.ShopViewModel
import com.frxuexi.shop.databinding.FragmentShopBinding
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayout.OnTabSelectedListener
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@AndroidEntryPoint
class ShopFragment : BaseFragment<FragmentShopBinding, ShopIntent, ShopViewModel>() {
    val shopAdapter by lazy { ShopAdapter() }
    val list = mutableListOf<ShopBeanItem>()
    var flag = false
    override fun getVM(): ShopViewModel {
        return viewModels<ShopViewModel>().value
    }

    override fun getBind(): FragmentShopBinding {
        return FragmentShopBinding.inflate(layoutInflater)
    }

    override fun initData() {
        lifecycleScope.launch {
            vm.uiState.collect {
                when (it) {
                    is UiState.onSuccess<*> -> {
                        when (it.type) {
                            RequestType.DEFAULT -> {
                                Log.i("lr", it.data.toString())
                                list.clear()
                                shopAdapter.data.clear()
                                val shopBean = it.data as ShopBean
                                list.addAll(shopBean.list)
                                shopAdapter.addData(list)
                                shopAdapter.notifyDataSetChanged()
                            }

                            RequestType.HOME -> {
                                val homeBean = it.data as HomeBean
                                binding.shopTab.removeAllTabs()
                                homeBean.explosiveMoney.apply {
                                    forEach {
                                        binding.shopTab.apply {
                                            addTab(newTab().setText(it.name))
                                            addOnTabSelectedListener(object :
                                                OnTabSelectedListener {
                                                override fun onTabSelected(tab: TabLayout.Tab?) {
                                                    vm.sendIntent(ShopIntent.getShops(get(tab?.position!!).type.toInt()))
                                                }

                                                override fun onTabUnselected(tab: TabLayout.Tab?) {
                                                }

                                                override fun onTabReselected(tab: TabLayout.Tab?) {
                                                }
                                            })
                                        }
                                    }
                                }
                            }

                            else -> {}
                        }
                    }

                    else -> {}
                }
            }
        }
    }

    override fun initView() {
        vm.sendIntent(ShopIntent.getHomeData)

        binding.shopRv.apply {
            adapter = shopAdapter
            layoutManager = StaggeredGridLayoutManager(2, RecyclerView.VERTICAL)
        }

        shopAdapter.setOnItemClickListener { adapter, view, position ->
            /*ARouter.getInstance().build("/shop/ShopDetailActivity")
                .withString("sid", shopAdapter.data.get(position).id.toString()).navigation(requireContext(),
                    object : NavigationCallback {
                    override fun onFound(postcard: Postcard?) {

                    }

                    override fun onLost(postcard: Postcard?) {
                        ToastUtils.showLong("找不到路径：${postcard?.path}")
                        postcard?.context.let {
                            ARouter.getInstance().build("/app/NoFoundActivity").navigation()
                        }
                    }

                    override fun onArrival(postcard: Postcard?) {
                    }

                    override fun onInterrupt(postcard: Postcard?) {
                    }
                })*/
            ArouterManager.navigation(requireContext(),"/shop/ShopDetailActivity","sid",shopAdapter.data.get(position).id.toString())
        }

        vm.sendIntent(ShopIntent.getShops(1))

        binding.shopSv.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                shopAdapter.apply {
                    data.clear()
                    if (s.isNullOrEmpty()) {
                        addData(list)
                    } else {
                        addData(list.filter { it.storeName.contains(s) })
                    }
                    notifyDataSetChanged()
                }
            }

            override fun afterTextChanged(s: Editable?) {
            }

        })

        binding.shopOrder.setOnClickListener {
            shopAdapter.apply {
                data.clear()
                if (flag) {
                    addData(list.sortedBy { it.price })
                } else {
                    addData(list.sortedByDescending { it.price })
                }
                notifyDataSetChanged()
            }
            flag = !flag
        }

        binding.shopFilter.setOnClickListener {
            val view = LayoutInflater.from(requireContext()).inflate(R.layout.pop, null)
            val popupWindow =
                PopupWindow(view, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)
            popupWindow.isFocusable = true
            popupWindow.showAtLocation(binding.shopFilter, Gravity.BOTTOM, 0, 0)
            view.findViewById<TextView>(R.id.price_one).setOnClickListener {
                shopAdapter.apply {
                    popupWindow.dismiss()
                    data.clear()
                    addData(list.filter { it.price <= 100 })
                    notifyDataSetChanged()
                }
            }
            view.findViewById<TextView>(R.id.price_two).setOnClickListener {
                shopAdapter.apply {
                    popupWindow.dismiss()
                    data.clear()
                    addData(list.filter { it.price in 100..500 })
                    notifyDataSetChanged()
                }
            }
            view.findViewById<TextView>(R.id.price_three).setOnClickListener {
                shopAdapter.apply {
                    popupWindow.dismiss()
                    data.clear()
                    addData(list.filter { it.price >= 500 })
                    notifyDataSetChanged()
                }
            }
            view.findViewById<TextView>(R.id.price_ok).setOnClickListener {
                val low = view.findViewById<TextView>(R.id.price_low).text?.toString()
                val high = view.findViewById<TextView>(R.id.price_high).text?.toString()
                var min = 0
                if (!low.isNullOrEmpty()) {
                    min = low.toInt()
                }
                var max = 0
                if (!high.isNullOrEmpty()) {
                    max = high.toInt()
                }
                shopAdapter.apply {
                    popupWindow.dismiss()
                    data.clear()
                    addData(list.filter { it.price in min..max })
                    notifyDataSetChanged()
                }
            }
        }
    }
}